import fs from "fs";
const filePath = "./data/pets/pets.json";
export async function writePetsInfo(petsInfo) {
  try {
    const existingPetsInfo = await readPetsInfo();
    const newPetsInfo = [...existingPetsInfo, petsInfo];
    fs.writeFileSync(filePath, JSON.stringify(newPetsInfo));
  } catch (error) {
    console.error("Error writing file info:", error);
  }
}
export async function deletePetsInfo(petsInfo) {
  try {
    const existingPetsInfo = await readPetsInfo();
    const newPetsInfo = existingPetsInfo.filter(
      (pet) => pet.title !== petsInfo.title
    );
    fs.writeFileSync(filePath, JSON.stringify(newPetsInfo));
  } catch (error) {
    console.error("Error deleting file info:", error);
  }
}
// read the pet information from the json file
export async function readPetsInfo() {
  try {
    // If the file does not exist, an empty array is returned
    const data = fs.readFileSync(filePath);
    return JSON.parse(data);
  } catch (error) {
    console.error("Error reading file info:", error);
    return [];
  }
}
//  根据指定的tokenId获取info
export async function getPetInfo(tokenId) {
  try {
    const petsArray = await readPetsInfo();

    return petsArray.filter((pet) => pet.tokenId === tokenId);
  } catch (error) {
    console.error("Error getting pet info:", error);
    return [];
  }
}
